package com.atguigu.chapter07.D02_WaterMark;

import com.atguigu.bean.WaterSensor;
import com.atguigu.util.AnqclnUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;

/**
 * Author: Pepsi
 * Date: 2023/8/7
 * Desc:
 *
 * flink保证数据不丢失的手段：
 *      1. 水印+事件时间
 *      2. 允许迟到  allowedLateness(Time.seconds(2))
 *      3. 侧输出流  sideOutputLateData(new OutputTag<WaterSensor>("late"){})
 *
 *
 */
public class Flink05_Sideout {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        env.setParallelism(1);

        // 设置水印生成的周期   水印两秒生成一次
        env.getConfig().setAutoWatermarkInterval(2000);

        SingleOutputStreamOperator<String> main = env
                .socketTextStream("hadoop101", 9999)
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                // 加水印  分配时间戳和水印
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                // 指明时间戳怎么来
                                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                                    @Override
                                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                        return element.getTs();
                                    }
                                })
                                .withIdleness(Duration.ofSeconds(5))  //解决数据倾斜导致的水印不更新问题，如果某个并行度水印超过5s没有更新，则以其他的为准
                )
                .keyBy(WaterSensor::getId)
                //  用滚动的事件窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .sideOutputLateData(new OutputTag<WaterSensor>("late"){})
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    // 在允许迟到的那块时间里，每来一个迟到的元素，这个方法就会执行一次
                    // 所以如果是全量的数据在iterable里面的话就会出现重复计算问题
                    @Override
                    public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        List<WaterSensor> list = AnqclnUtil.toList(elements);
                        String startTime = AnqclnUtil.toDateTime(context.window().getStart());
                        String endTime = AnqclnUtil.toDateTime(context.window().getEnd());
                        out.collect(s + " " + startTime + " " + endTime + " " + list);
                    }
                });

        main.print("main >");
        main.getSideOutput(new OutputTag<WaterSensor>("late"){}).print("late");

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
